#!/usr/bin/env bash

s=$(which sleep)

t='<?xml version="1.0" standalone="yes"?>
<tp2package>
<name>test_filter_pkg</name>
<version>1.0.0</version>
<description>Test package for sleep</description>
<files>'

t2='</files>
</tp2package>'

dd=$(dirname $s)
flist=$(ls $dd/s*)
fst_two=$(ls $dd/s* | head -2)
hostname=$(hostname)YY

o=$(whoami)
g=$(id | perl -ne '/.*\((.*?)\).*\((.*?)\).*/; print $2')

if [[ -d tt ]]
then
	rm -rf tt
fi

mkdir tt 
exec >tt/test_01.xml
cp $dd/s* tt
echo "$t"
x=0
for f in $flist
do
	if ((x<2))
	then
		echo "<file perms=\"755\" owner=\"$o\" filter_hostname=\"$hostname\" group=\"$g\">$(basename $f)</file>";
	else
		echo "<file perms=\"755\" owner=\"$o\" group=\"$g\">$(basename $f)</file>";
	fi
	((x=x+1))
done
echo "$t2"
 
cd tt
tp2pkg --overwrite --config test_01.xml --verbose --repos /tmp || exit 1

# Remove tt_test_01 namespace if it exists

../../../bin/tp2remove_ns --namespace tt_test_01 --leave

mkdir pkg_root

# Create the new namespace.
../../../bin/tp2make_ns --owner $o --root $PWD/pkg_root --name tt_test_01 --nosqlite || exit 1 

# Install the package.
../../../bin/tp2install --namespace tt_test_01 --pkg test_filter_pkg --verbose --repos /tmp --reinstall  --force

[[ $? -ne 0 ]] && exit 1

# Check the first two files do not exist

for ff in $fst_lst
do
	if [[ -f pkg_root/$ff ]]
	then
		echo "Error: File pkg_root/$ff exists and should not."
	fi
done

# Perform verification - and check no missing giles

o=$(../../../bin/tp2verify --namespace tt_test_01 2>&1 | grep 'Missing file:')

if [[ -n "$o" ]]
then
	echo "Error: Missing file errors where none expected."
	exit 1
fi

exit 0
